// pages/user/address/address.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    addrList: null,
    info: {},
    radioHide: false,
    prePage: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let pages = getCurrentPages(),
        prePage = pages[pages.length - 2].route
    this.setData({
      prePage: prePage
    })
    if (options.info) {
      this.setData({
        info: JSON.parse(options.info)
      })
    }
    if (app.isEmptyObject(this.data.info)) {
      this.setData({
        radioHide: true
      })
    }

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.initApp()
  },

  /**
   * init
   */
  initApp: function() {
    let that = this
    wx.showLoading({
      title: app.globalData.loadText,
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function(accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1/customer/addr?access_token=' + accessToken,
        success: res => {
          if (res.data.status === 1) {
            that.setData({
              addrList: res.data.data.addr
            })
            wx.hideLoading()
          }
        }
      })
    })
  },

  addAdress: function() {
    wx.navigateTo({
      url: './add/add',
    })
  },

  /**
   * 修改地址
   */
  updateAddress: function(e) {
    wx.navigateTo({
      url: './add/add?&add_id=' + e.currentTarget.dataset.id,
    })
  },

  /**
   * 删除地址
   */
  delAddress: function(e) {
    let that = this
    wx.showModal({
      title: '警告',
      content: '确认删除',
      success: res => {
        if (res.confirm) {
          wx.showLoading({
            mask: true,
            title: app.globalData.loadText,
          })
          app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function(accessToken) {
            wx.request({
              url: app.globalData.hostAPI + '/v1/addr/delete?access_token=' + accessToken + '&id=' + e.currentTarget.dataset.id,
              success: res => {
                that.initApp()
                wx.hideLoading()
              }
            })
          })
        }
      }
    })

  },

  /**
   * 设置默认地址
   */
  setDefault: function(e) {
    let that = this
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function(accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1/addr/set-default?access_token=' + accessToken,
        data: {
          addr_id: e.currentTarget.dataset.id
        },
        success: res => {
          if (res.data.status === 1) {
            that.initApp()
          }
        }
      })
    })

  },

  /**
   * 选择地址返回
   */
  selAddr: function(e) {
    let that = this,
        add = e.currentTarget.dataset.add
    that.setData({
      'info.address': add
    })
    console.log(add)
    console.log(that.data.info.address)
    wx.reLaunch({
      url: '/' + that.data.prePage + '?info=' + JSON.stringify(that.data.info),
    })
  }
})